import { ref, onUnmounted } from 'vue';
const mediaRecorder = ref(null);// 媒体录制器
const audioChunks = ref([]);// 音频片段
const audioUrl = ref('');// 音频URL
const recognition = ref(null);// 语音识别器
const transcript = ref('');// 识别结果
const errorMessage = ref('');// 错误信息
const isRecording = ref(false);// 是否正在录音
const isPaused = ref(false);// 是否暂停
const audioContext = ref(null);// 音频上下文
const analyser = ref(null);// 分析器
const source = ref(null);// 音频源
const animationId = ref(null);// 动画ID

/**
 * 启动录音
 * @returns {Promise<void>}
 */
const startRecording = async () => {
  if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
    alert('该浏览器不支持音频捕获功能。');
    return;
  }

  if (!('webkitSpeechRecognition' in window) && !('SpeechRecognition' in window)) {
    alert('该浏览器不支持语音识别功能。');
    return;
  }

  try {
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    mediaRecorder.value = new MediaRecorder(stream);
    audioChunks.value = [];

    mediaRecorder.value.ondataavailable = (event) => {
      audioChunks.value.push(event.data);
    };

    mediaRecorder.value.onstop = () => {
      const audioBlob = new Blob(audioChunks.value, { type: 'audio/wav' });
      audioUrl.value = URL.createObjectURL(audioBlob);
    };

    mediaRecorder.value.start();
    let text=startRecognition();

    audioContext.value = new (window.AudioContext || window.webkitAudioContext)();
    analyser.value = audioContext.value.createAnalyser();
    source.value = audioContext.value.createMediaStreamSource(stream);
    source.value.connect(analyser.value);

    isRecording.value = true;
    isPaused.value = false;
    monitorVolume();

    return text;

  } catch (error) {
    console.error('获取麦克风权限失败:', error);
    if (error.name === 'NotAllowedError' || error.name === 'PermissionDeniedError') {
      errorMessage.value = '麦克风访问被拒绝，请检查浏览器设置并启用麦克风权限。';
    } else if (error.name === 'NotFoundError' || error.name === 'DevicesNotFoundError') {
      errorMessage.value = '未找到麦克风设备，请连接麦克风并重试。';
    } else {
      errorMessage.value = '发生未知错误，请重试。';
    }
  }
};
/**
 *  暂停录音
 */
const pauseRecording = () => {
  if (mediaRecorder.value && isRecording.value) {
    mediaRecorder.value.pause();
    if (recognition.value) {
      recognition.value.stop();
    }
    isPaused.value = true;
  }
};

const resumeRecording = () => {
  if (mediaRecorder.value && isPaused.value) {
    mediaRecorder.value.resume();
    if (recognition.value) {
      recognition.value.start();
    }
    isPaused.value = false;
  }
};
/**
 * 检测麦克风音量
 */
const monitorVolume = () => {
  const bufferLength = analyser.value.fftSize;
  const dataArray = new Uint8Array(bufferLength);
  const checkVolume = () => {
    analyser.value.getByteTimeDomainData(dataArray);
    let sum = 0;
    for (let i = 0; i < bufferLength; i++) {
      sum += (dataArray[i] - 128) * (dataArray[i] - 128);
    }
    const volume = Math.sqrt(sum / bufferLength);

    if (volume > 1) {
      isRecording.value = true;
      if (recognition.value && !isPaused.value) {
        recognition.value.start();
      }
    } else {
      isRecording.value = false;
    }

    animationId.value = requestAnimationFrame(checkVolume);
  };

  checkVolume();
};
/**
 * 启动语音识别
 */
const startRecognition = () => {
  recognition.value = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
  recognition.value.lang = 'zh-CN';
  recognition.value.continuous = true;
  recognition.value.interimResults = true;

  recognition.value.onresult = (event) => {
    let interimTranscript = '';
    for (let i = event.resultIndex; i < event.results.length; i++) {
      const transcriptPart = event.results[i][0].transcript;
      if (event.results[i].isFinal) {
        transcript.value += transcriptPart;
      } else {
        interimTranscript += transcriptPart;
      }
    }
  };

  recognition.value.onerror = (event) => {
    console.error('Recognition error:', event.error);
  };

  recognition.value.onend = () => {
    console.log('语音识别结束');
    return recognition.value
    // 如果不是手动暂停，继续识别
    if (recognition.value && isRecording.value && !isPaused.value) {
      recognition.value.start();
    }
  };

  recognition.value.start();
};
/**
 * 停止录音
 */
const stopRecording = () => {
  if (mediaRecorder.value) {
    mediaRecorder.value.stop();
  }
  if (recognition.value) {
    recognition.value.stop();
  }
  if (audioContext.value) {
    audioContext.value.close();
  }
  cancelAnimationFrame(animationId.value);
  isRecording.value = false;
  isPaused.value = false;
};

onUnmounted(() => {
  if (audioContext.value) {
    audioContext.value.close();
  }
  cancelAnimationFrame(animationId.value);
});